package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.atguigu.gmall.rabbit.constant.MqConst;
import com.atguigu.gmall.rabbit.service.RabbitService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    //查询一级分类集合
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
                .eq("category1_id",category1Id));
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id",category2Id));
    }

    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id,category2Id,category3Id);
    }

    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //1.平台属性表
        baseAttrInfoMapper.insert(baseAttrInfo);

        //2.平台属性值表
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (attrValueList != null && attrValueList.size() > 0){
            attrValueList.forEach(attrValue -> {
                //外键
                attrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(attrValue);
            });
        }
    }

    //分页查询品牌集合
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        return baseTrademarkMapper.selectPage(new Page<>(page,limit), null);
    }

    //获取商品集合分类分页查询
    @Override
    public IPage findSpuList(Integer page, Integer limit, Long category3Id) {
        return spuInfoMapper.selectPage(new Page<>(page,limit),
                new QueryWrapper<SpuInfo>().eq("category3_id",category3Id));
    }

    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    //保存spu
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //商品表
        spuInfoMapper.insert(spuInfo);
        //图片表（总图片）
        spuInfo.getSpuImageList().forEach(spuImage -> {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
        //销售属性表
        spuInfo.getSpuSaleAttrList().forEach(spuSaleAttr -> {
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //销售属性值表
            spuSaleAttr.getSpuSaleAttrValueList().forEach(spuSaleAttrValue -> {
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });

    }

    //查询spu所有的图片显示在sku添加页面上，供其选择
    @Override
    public List<SpuImage> spuImageList(Long spuId) {

        return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id",spuId));
    }

    //根据spuid查询所有的销售属性及属性值表
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }

    //保存sku
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //默认是下架状态
        skuInfo.setIsSale(SkuInfo.NOSALE);
        //1.库存表
        skuInfoMapper.insert(skuInfo);
        //2.库存的图片表
        skuInfo.getSkuImageList().forEach(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        //3.库存的平台属性表
        skuInfo.getSkuAttrValueList().forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //4.库存的销售属性表
        skuInfo.getSkuSaleAttrValueList().forEach(skuSaleAttrValue -> {
            //skuId
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            //spuId
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
    }

    @Override
    public IPage skuList(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page<>(page,limit),null);
    }


    @Autowired
    private RabbitService rabbitService;

    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);
        skuInfoMapper.updateById(skuInfo);
        // 将来 保存数据到ES中
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_UPPER, skuId);
    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.NOSALE);
        skuInfoMapper.updateById(skuInfo);
        // 将来 删除es中的数据
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER, skuId);
    }

    //根据三级分类  查询一二三级分类
    @Override
    @GmallCache(prefix = "getBaseCategoryView")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    //根据三级分类  查询一二三级分类
   /* @Override
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        //查询缓存
        String cacheKey = RedisConst.SKUKEY_PREFIX + category3Id + RedisConst.SKUKEY_SUFFIX + ":category3Id";
        BaseCategoryView baseCategoryView = (BaseCategoryView)redisTemplate.opsForValue().get(cacheKey);
        if (baseCategoryView != null){
            return baseCategoryView;
        } else {
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + category3Id + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            try {
                boolean tryLock = lock.tryLock(1, 2, TimeUnit.SECONDS);//过期不候型
                if (tryLock){
                    //查询
                    baseCategoryView = baseCategoryViewMapper.selectById(category3Id);
                    if (baseCategoryView != null){
                        //保存到Redis缓存中
                        redisTemplate.opsForValue().set(cacheKey,baseCategoryView,
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), TimeUnit.SECONDS);
                    }else {
                        //缓存穿透
                        baseCategoryView = new BaseCategoryView();
                        //解决穿透
                        redisTemplate.opsForValue().set(cacheKey,baseCategoryView,5, TimeUnit.MINUTES);
                    }
                }else {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return (BaseCategoryView)redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
        return baseCategoryView;
    }
*/
    @Autowired
    private RedissonClient redissonClient;

    //查询sku中的信息 sku_info    查询sku中的图片 sku_image

    @GmallCache(prefix = "getSkuInfo")//自定义缓存注解
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //1.skuInfo  主键
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null){
            //2.skuImage  外键
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                    .eq("sku_id", skuId));
            skuInfo.setSkuImageList(skuImageList);
        }
        return skuInfo;
    }


   /* @GmallCache(prefix = "getSkuInfo")//自定义缓存注解
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo)redisTemplate.opsForValue().get(cacheKey);
        if (null != skuInfo){
            return skuInfo;
        }else {
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            //lock.lock();//不见不散型
            //参数1：表示过期时间，参数2：获取到锁之后锁的过期时间，防止死锁，参数3：时间单位
            try {
                boolean tryLock = lock.tryLock(1, 2, TimeUnit.SECONDS);//过期不候型
                if (tryLock){
                    //分开进行两个单表查询不好，这样会向数据库发送两条语句，有可能会造成资源的浪费，最好应该自己写sql语句进行关联查询（待优化）
                    //1.skuInfo  主键
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if (skuInfo != null){
                        //2.skuImage  外键
                        List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                .eq("sku_id", skuId));
                        skuInfo.setSkuImageList(skuImageList);
                        //保存在Redis缓存中一份   解决缓存雪崩问题： new Random().nextInt(300)
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), TimeUnit.SECONDS);
                    }else {
                        //缓存穿透
                        skuInfo = new SkuInfo();
                        //解决穿透
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,5, TimeUnit.MINUTES);
                    }
                }else {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return (SkuInfo)redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
        return skuInfo;
    }
*/




    /*@Override
    public SkuInfo getSkuInfo(Long skuId) {
        //查询缓存
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo)redisTemplate.opsForValue().get(cacheKey);
        if (null != skuInfo){
            return skuInfo;
        } else {
            //上分布式锁，解决缓存击穿问题
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            //设置过期时间，添加uuid防止删除锁时误删其他的锁
            String uuid = UUID.randomUUID().toString();
            Boolean isLock = redisTemplate.opsForValue().setIfAbsent(cacheLockKey, uuid,3,TimeUnit.SECONDS);
            if (isLock){//拿到锁
                //分开进行两个单表查询不好，这样会向数据库发送两条语句，有可能会造成资源的浪费，最好应该自己写sql语句进行关联查询（待优化）
                //1.skuInfo  主键
                skuInfo = skuInfoMapper.selectById(skuId);
                if (skuInfo != null){
                    //2.skuImage  外键
                    List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                            .eq("sku_id", skuId));
                    skuInfo.setSkuImageList(skuImageList);
                    //保存在Redis缓存中一份   解决缓存雪崩问题： new Random().nextInt(300)
                    redisTemplate.opsForValue().set(cacheKey,skuInfo,
                            RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), TimeUnit.SECONDS);

                    //删除锁 （相当于解锁）
                    String u = (String) redisTemplate.opsForValue().get(cacheLockKey);
                    //删除锁之前先判断
                   *//* if (uuid.equals(u)) {
                        redisTemplate.delete(cacheLockKey);
                    }*//*

                    // 2. 释放锁 del LUA 脚本
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                    this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLockKey), uuid);

                }else {
                    //缓存穿透
                    skuInfo = new SkuInfo();
                    //解决穿透
                    redisTemplate.opsForValue().set(cacheKey,skuInfo,5, TimeUnit.MINUTES);
                }
            }else {
                //没拿到锁  ，继续获取锁
                try {
                        TimeUnit.SECONDS.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                return (SkuInfo)redisTemplate.opsForValue().get(cacheKey);
            }
        }
        return skuInfo;
    }*/

    //查询价格
    @Override
    public BigDecimal getPrice(Long skuId) {
        //待优化，应该只查价格单独写sql语句
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null){
            return skuInfo.getPrice();
        }
        return null;
    }

    //查询spu中总销售属性及属性值 同时选中一个默认商品
    @Override
    @GmallCache(prefix = "getSaleAttrAndValueAndChecked")
    public List<SpuSaleAttr> getSaleAttrAndValueAndChecked(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSaleAttrAndValueAndChecked(skuId, spuId);
    }

    /*@Override
    public List<SpuSaleAttr> getSaleAttrAndValueAndChecked(Long skuId, Long spuId) {
        //查询缓存
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX + ":SpuSaleAttr";
        List<SpuSaleAttr> saleAttrAndValueAndChecked = (List<SpuSaleAttr>) redisTemplate.opsForValue().get(cacheKey);
        if (saleAttrAndValueAndChecked != null){
            return saleAttrAndValueAndChecked;
        }else {
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);

            try {
                boolean tryLock = lock.tryLock(1, 2, TimeUnit.SECONDS);//过期不候型
                if (tryLock){
                    saleAttrAndValueAndChecked = spuSaleAttrMapper.getSaleAttrAndValueAndChecked(skuId, spuId);
                    if (saleAttrAndValueAndChecked != null){
                        redisTemplate.opsForValue().set(cacheKey,saleAttrAndValueAndChecked,
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300),TimeUnit.SECONDS);
                    }else {
                        saleAttrAndValueAndChecked = new ArrayList<>();
                        redisTemplate.opsForValue().set(cacheKey,saleAttrAndValueAndChecked,5,TimeUnit.MINUTES);
                    }
                } else {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return (List<SpuSaleAttr>)redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
        return saleAttrAndValueAndChecked;
    }
*/

    @Override
    @GmallCache(prefix = "getSkuValueIdsMap")
    public Map<String, String> getSkuValueIdsMap(Long spuId) {
        List<Map<String,Object>> listMap = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        Map<String,String> result = new HashMap<>();
        listMap.forEach(map -> {
            result.put(String.valueOf(map.get("value_ids")),String.valueOf(map.get("sku_id")));
        });
        return result;
    }

    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }

    //根据skuId 查询sku_attr_value  base_attr_info  base_attr_value
    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }


}
